﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using yiCommerce.Core;
using yiCommerce.Core.Domain.Customers;
using yiCommerce.Service.Authentication;
using yiCommerce.Service.Customers;
using yiCommerce.Service.Messages;

namespace yiCommerce.Controllers.api
{
    public class LoginApiController : ApiController
    {

        private ICustomerRegistrationService _customerRegistrationService;
        private IAuthenticationService _authenticationService;
        private ICustomerService _customerService;
        private IMessageService _messageService;
        public LoginApiController(ICustomerRegistrationService customerRegistrationService, IAuthenticationService authenticationService, ICustomerService customerService, IMessageService messageService)
        {
            _customerRegistrationService = customerRegistrationService;
            _authenticationService = authenticationService;
            _customerService = customerService;
            _messageService = messageService;
        }

        public LoginResult Login(LoginRequest request)
        {
            var result = new LoginResult();

            if (_customerRegistrationService.ValidateCustomer(
                request.Email, request.Password))
            {
                var customer = _customerService.GetCustomerByEmail(request.Email);
                _authenticationService.SignIn(customer, true);

                result.Status = ConstInfo.ResultSuccessStatus;
                result.Message = _messageService.GetResourceValue(Messages.CustomerRegistrationService_ValidateCustomer_LoginSuccess, 0);
                result.RedirectUrl = Url.Route("statushomepage", new {customerid = customer.Id});
            }
            else
            {

                result.Status = ConstInfo.ResultFailedStatus;
                result.Message = _messageService.GetResourceValue(Messages.CustomerRegistrationService_ValidateCustomer_LoginFailed, 0);
            }
            return result;
        }
    }

    public class LoginRequest
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class LoginResult
    {
        public string Status { get; set; }
        public string Message { get; set; }
        public string RedirectUrl { get;set; }
    }
}
